package reittiopas;



import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.Vector;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

/**
*
* @author Jaakko, Petteri
*/
public class ReittiopasMidlet extends MIDlet implements CommandListener, ItemStateListener {

    private Command exitCommand;
    private Command getRouteCommand;
    private Command backCommand;
    private Command editFavouritesCommand;
    private Command saveFavouritesCommand;
    private Vector favorites;
    
    private Display display;
    private Form startForm;
    private Form resultForm;
    private Form editFavouritesForm;
    private int maxFavourites = 3;
    
    private TextField startAddressField;
    private TextField destAddressField;
   
    private ChoiceGroup timeChoice;
    private DateField dateTimeField;
    
    private RouteFavoritesManager favoritesManager;
    private ChoiceGroup startFavorites;
    private ChoiceGroup destFavorites;
    //private FavouritesManager fm;
    
    private Controller controller;

    public ReittiopasMidlet() {
        
    	favoritesManager = new RouteFavoritesManager();
    	favorites = new Vector();
    	
    	//fm = new FavouritesManager();
    	
    	exitCommand = new Command("Exit", Command.EXIT, 0);
        getRouteCommand = new Command("Get Route", Command.OK, 3);  // 3 is priority of command
        backCommand = new Command("Back", Command.BACK, 1);
        editFavouritesCommand = new Command("Edit favourites", Command.OK, 2);
        saveFavouritesCommand = new Command("Save favourites", Command.OK, 2);
        
        Command cHome = new Command("Home", Command.ITEM, 3);
        favorites.addElement(cHome);
        Command cSchool = new Command("School", Command.ITEM, 3);
        favorites.addElement(cSchool);
        
        display = Display.getDisplay(this);
        controller = new Controller(new RouteService(), new TimeFormatter());
       
    }
    
    public void startApp() {
        startScreen();
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command c, Displayable s) {
        
    	if (c == exitCommand) {
            destroyApp(false);
            notifyDestroyed();
        }
        else if (c == getRouteCommand) {
            routeScreen();
        }
        else if (c == backCommand) {
        	startScreen();
        }
        else if (c==editFavouritesCommand) {
        	editFavourites();
        }
        else if(c==saveFavouritesCommand) {
        	saveFavourites();
        	startScreen();
        }
    	
    	
//    	//these are for users' favorite routes e.g. "Home"
//        else {
//        	
//        	for(int i = 0; i<favorites.size(); i++) {
//        		
//        		if(c == (Command) favorites.elementAt(i)) {
//        			
//        			String routeName = ((Command)favorites.elementAt(i)).getLabel();
//        			String startAddress = favoritesManager.getStartAddress(routeName);
//        			this.startAddressField.setString(startAddress);
//        			
//        			String destAddress = favoritesManager.getDestinationAddress(routeName);
//        			this.destAddressField.setString(destAddress);
//        			
//        		}
//        	}
//        }
    	
    }
    
   
    
    /**
     * Creates and sets the start screen
     */
    private void startScreen() {
    	///////////////////////
    	RecordManager rm = new RecordManager("reittiopastesti1");
    	Vector favs = rm.getRecords();
    	System.out.println(favs);
    	
    	startFavorites = new ChoiceGroup("", Choice.EXCLUSIVE);
    	startFavorites.append("Address field", null);
    	for(int i=0; i < favs.size() && i < maxFavourites; i++)
    		startFavorites.append((String)favs.elementAt(i), null);
    	
    	destFavorites = new ChoiceGroup("", Choice.EXCLUSIVE);
    	destFavorites.append("Address field", null);
    	for(int i=0; i < favs.size() && i < maxFavourites; i++)
    		destFavorites.append((String)favs.elementAt(i), null);
    	   	
    	////////////////////
    	
    	
        startForm = new Form ("Get route");
        startAddressField = new TextField("Start address", "", 40, TextField.ANY);
        destAddressField = new TextField("Destination address", "", 40, TextField.ANY);
        dateTimeField = new DateField("", DateField.DATE_TIME);
        dateTimeField.setDate(new Date(System.currentTimeMillis()));
        timeChoice = new ChoiceGroup("", Choice.EXCLUSIVE);
        timeChoice.append("Departure time", null);
        timeChoice.append("Arrival time", null);
        	
        startForm.append(startAddressField);
        startForm.append(startFavorites);
        startForm.append(destAddressField);
        startForm.append(destFavorites);
        
       
        startForm.append(dateTimeField);
        startForm.append(timeChoice);
        startForm.addCommand(exitCommand);
        startForm.addCommand(getRouteCommand);
        startForm.addCommand(editFavouritesCommand);
        
         
//        for(int i = 0; i<favorites.size(); i++) {
//        	
//        	startForm.addCommand(((Command)favorites.elementAt(i)));
//        	
//        }

        startForm.setCommandListener(this);
        
        startForm.setItemStateListener(this);
        
        
        display.setCurrent(startForm);
    }

    /**
     * Asks the route from controller, creates the result screen and sets it visible.
     */
    private void routeScreen() {
//    	Form loadingForm = new Form("Getting route...");
//    	Ticker loading = new Ticker("........");
//    	loadingForm.setTicker(loading);
//    	display.setCurrent(loadingForm);
//    	

        boolean isStartTime = false;
        if(timeChoice.getSelectedIndex() == 0) {
        	isStartTime = true;
        }
        
        Calendar cal = Calendar.getInstance();
        cal.setTime(dateTimeField.getDate());
        int hour = cal.get(Calendar.HOUR);
        if (cal.get(Calendar.AM_PM) == Calendar.PM)
        	hour += 12;
        String time = "" + hour + ":" + cal.get(Calendar.MINUTE);
        
        
        String year = ""+ cal.get(Calendar.YEAR);
        String month = ""+ (cal.get(Calendar.MONTH) + 1);  //months are indexed from 0...11
        String day = "" + cal.get(Calendar.DAY_OF_MONTH);
        if(month.length() == 1)
        	month = "0" + month;
        if(day.length() == 1)
        	day = "0" + day;
        
        
        String date =   ""+year+month+day;
        
        String startAddress, destAddress;
        if(startFavorites.getSelectedIndex() == 0) {
        	startAddress = this.startAddressField.getString();
        }
        else {
        	startAddress = startFavorites.getString(startFavorites.getSelectedIndex());
        }
        if(destFavorites.getSelectedIndex() == 0) {
        	destAddress = this.destAddressField.getString();
        }
        else {
        	destAddress = destFavorites.getString(destFavorites.getSelectedIndex());
        }
        
    	Vector routes = controller.getRoutes(startAddress, destAddress, time, date, isStartTime);
    	
    	if(routes != null) {
    		String routeString = "";
    		for(int j = 0; j < routes.size(); j++) {
	    		Route route = (Route)routes.elementAt(j);
	    		//routeString += "==============\nRoute " + (j+1) + "\n";
	    		routeString += route;
	    		for(int i = 0; i<route.getSubRoutes().size(); i++) {
	    			SubRoute subroute = (SubRoute)route.getSubRoutes().elementAt(i);
	    			routeString += subroute.getFullDescription();
    			}
	    		SubRoute last = (SubRoute)route.getSubRoutes().lastElement();
	    		routeString += ""+last.getArrivalTime() + " " + last.getDestinationLocation().getFullAddress() + "\n";
	    		routeString += "====================\n";
    		}
    		resultForm = new Form ("Route");
            resultForm.addCommand(exitCommand);
            resultForm.addCommand(backCommand);
            resultForm.setCommandListener(this);
    		resultForm.append(routeString);
    		display.setCurrent(resultForm);
    	}
    	else {
    		//resultForm.append("Route not found. Check the address.");
    		Alert alert = new Alert("Route not found", "Route not found. Please check the addresses.", null, AlertType.WARNING); 
        	        alert.setTimeout(Alert.FOREVER); 
        	        display.setCurrent(alert); 
    	}
    	
    }
    
    private void editFavourites() {
    	editFavouritesForm = new Form("Edit favourites");

    	RecordManager rm = new RecordManager("reittiopastesti1");
    	Vector favs = rm.getRecords();
    	System.out.println("From edit favourites: " + favs);
    	
    	for(int i=0; i < maxFavourites; i++)
    		if (i < favs.size())
    			editFavouritesForm.append(new TextField("Favourite " + (i+1) + ":", (String)favs.elementAt(i), 40, TextField.ANY));
    		else
    			editFavouritesForm.append(new TextField("Favourite " + (i+1) + ":", "", 40, TextField.ANY));
    	editFavouritesForm.addCommand(backCommand);
    	editFavouritesForm.addCommand(saveFavouritesCommand);
    	editFavouritesForm.setCommandListener(this);
    	display.setCurrent(editFavouritesForm);
    }
    
    private void saveFavourites() {
    	RecordManager rm = new RecordManager("reittiopastesti1");
    	rm.clearRecords();
    	for (int i = 0;  i < editFavouritesForm.size() && i < maxFavourites; i++) {
    		TextField tf = (TextField)editFavouritesForm.get(i);
    		if(tf != null) {
    			rm.addRecord(tf.getString());
    		}
    	}
    }
    
    public void itemStateChanged(Item item) 
    {
    	
    	if(item.equals(this.startAddressField)){
    		
    	}
    	
    	if(item.equals(this.destAddressField)) {
    		
    	}
    	
    }
    
    

}